package com.ca.singlesignon.controller;
import com.ca.singlesignon.entity.UserEntity;
import com.ca.singlesignon.service.UserService;
import com.ca.singlesignon.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private RedisPoolUtil redisPoolUtil;
    @Autowired
    private RedisShardedPoolUtil redisShardedPoolUtil;

    @PostMapping(value = "login")
    @ResponseBody
    public ServerResponse<UserEntity> login(String username, String password, HttpSession session,
                                            HttpServletResponse httpresponse) {
        ServerResponse<UserEntity> response = userService.login(username, password);
        if (response.isSuccess()) {

            //tem2:获取的用户信息不放在session中,存放到redis中
            //redisPoolUtil.setEx(session.getId(), JsonUtil.obj2String(response.getData()), 30 * 60);

            //1、把sessionId 存放在cookie中
             CookieUtil.writeLoginToken(httpresponse,session.getId());
            //2、把User转换成json存放到redis
            String userStr = JsonUtil.obj2String(response.getData());
            //redisPoolUtil.setEx(session.getId(),userStr,60*30);
            redisShardedPoolUtil.setEx(session.getId(),userStr,60*30);
        }
        return response;
    }
    @GetMapping(value = "get_user_info")
    @ResponseBody
    public ServerResponse<UserEntity> getUserInfo(HttpServletRequest httpRequest) {

        //tem2 从redis获取信息sessionId
        //String key=httpRequest.getSession().getId();

        //先从cookies中获取到redis的key
        String key = CookieUtil.readLoginToken(httpRequest);

        if(StringUtils.isEmpty(key)){
            return ServerResponse.createByErrorMessage("用户未登录,无法获取当前信息");
        }
        // String userStr = redisPoolUtil.get(key);
        String userStr = redisShardedPoolUtil.get(key);
        UserEntity user = JsonUtil.string2Obj(userStr, UserEntity.class);
        if (user != null) {
            return ServerResponse.createBySuccess(user);
        }
        return ServerResponse.createByErrorMessage("用户未登录,无法获取当前信息");
    }

}
